package com.jsjosem.aftersales.request;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.util.Consumer;

import com.jsjosem.aftersales.InitApplication;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.cache.UserCache;
import com.jsjosem.aftersales.data.response.AbstractResponse;
import com.jsjosem.aftersales.data.response.BaseResponse;

import org.nd4j.shade.jackson.core.type.TypeReference;
import org.nd4j.shade.jackson.databind.ObjectMapper;

import java.util.Objects;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class AsyncRequest<RES> {

    final Retrofit retrofit;

    private final static String TAG = AsyncRequest.class.getName();

    public AsyncRequest() {
        this.retrofit = RetrofitClient.getInstance();
    }

    /**
     * 发送网络请求(异步)
     *
     * @param call call
     */
    public void sendRequest(Call<RES> call, Consumer<RES> success, Consumer<? super Object> failed) {
        call.enqueue(new Callback<RES>() {
            @Override
            public void onResponse(@NonNull Call<RES> call, @NonNull Response<RES> response) {

                try {
                    ResponseBody errorBody = response.errorBody();
                    if (errorBody != null) {
                        Log.w("Http Response", "请求响应错误");
                        byte[] bytes = errorBody.bytes();
                        BaseResponse<RES> baseResponse = new ObjectMapper().readValue(bytes, new TypeReference<BaseResponse<RES>>() {
                        });
                        failed.accept(baseResponse.getMsg());
                        return;
                    }
                } catch (Exception e) {
                    Log.e("Http Response", "请求响应错误", e);
                    failed.accept("网络异常，请稍后重试");
                    return;
                }
                if (response.body() == null) {
                    success.accept(null);
                    return;
                }
                AbstractResponse body = (AbstractResponse) response.body();
                if (body.getCode() == 401) {
                    UserCache instance = UserCache.getInstance();
                    if (Objects.nonNull(instance)) {
                        instance.logout();
                        InitApplication.startLogin();
                        return;
                    }
                }
                if (body.getCode() != 0) {
                    failed.accept(body.getMsg());
                    return;
                }
                success.accept(response.body());
            }

            @Override
            public void onFailure(@NonNull Call<RES> call, @NonNull Throwable t) {
                Log.e(TAG, "request failed", t);
            }
        });
    }
}